var express = require('express');
var router = express.Router();
const mysqlExec = require('../db/dbMysql');
let {
    Msg,
    curPath
} = require('../tools/msg.js');

//列表页中的城市接口
router.get('/city', async function (req, res) {
    let sql = `select * from e_area`;
    let [err, arr] = await mysqlExec(sql);
    if (err) {
        res.send(Msg(200, '城市查询成功', arr));
    } else {
        res.send(Msg(500, '城市查询失败'));
    }
})

//列表页中的年级接口
router.get('/grade', async (req, res) => {
    let sql=`select * from e_grade`;
    let [err,arr]=await mysqlExec(sql);
    if(err){
        res.send(Msg(200,'年级查询成功',arr));
    }else{
        res.send(Msg(500,'年级查询失败'));
    }
})

//列表页中的学科接口
router.get('/subject', async (req, res) => {
    let sql=`select * from e_subject`;
    let [err,arr]=await mysqlExec(sql);
    if(err){
        res.send(Msg(200,'学科查询成功',arr));
    }else{
        res.send(Msg(500,'学科查询失败'));
    }
})

//列表页中的类别接口
router.get('/category', async (req, res) => {
    let sql=`select * from e_category`;
    let [err,arr]=await mysqlExec(sql);
    if(err){
        res.send(Msg(200,'类别查询成功',arr));
    }else{
        res.send(Msg(500,'类别查询失败'));
    }
})

//列表页中的课程接口
router.get('/courslist',async(req,res)=>{
    //cid:课程类别(1为同步课程 2为精品课程)
    //limits:每页要显示的条数
    //pages:第几页
    //city:城市
    //grade:年级
    //subject:学科
    //category:.
    let {cid=1,limits=6,pages=1,city='',grade='',subject='',category=''} =req.query;
    //游标位置
    let start=(pages-1)*limits;
    let where='';
    if(city){
        where +=` and area_name='${city}' `;
    }
    if(grade){
        where +=` and grade_name='${grade}' `;
    }
    if(subject){
        where += ` and subject_name='${subject}' `;
    }
    if(category){
        where +=` and category_name='${category}' `
    }

    //查询课程数据
    let sql=`select cid,title,price,concat('${curPath}course/',image_src) as image_src,area_name,subject_name from e_course where type='${cid}' ${where} limit ${start},${limits}`;
    let [err,arr]=await mysqlExec(sql);
    if(err){
        sql=`select count(cid) as num from e_course where type='${cid}' ${where} `;
        let [e ,datas]=await mysqlExec(sql);
        if(e){
            arr.unshift(datas[0].num);
        }else{
            arr.unshift(0);
        }
        res.send(Msg(200, '列表页中的课程查询成功', arr))
    }else{
        res.send(Msg(500, '列表页中的课程查询失败'));
    }
})
module.exports = router;